package main

import (
	"fmt"
	"giteehook/hook"
	jsoniter "github.com/json-iterator/go"
	"log"
	"net/http"
	"os"
	"strconv"
)

type SysConfig struct {
	Sys SysCon		`json:"sys"`
}
type SysCon struct {
	MonitorPort int	`json:"monitor_port"`
}
var sysConf = &SysConfig{}

func init(){
	b, err := loadConf("config/tsconfig.json")
	if err != nil {
		panic(err)
	}

	if err = hook.InitHook(b); err != nil{
		panic(err)
	}

	if err = jsoniter.Unmarshal(b, sysConf); err != nil{
		panic(fmt.Errorf("系统 配置解析错误:%w", err))
	}
	if sysConf.Sys.MonitorPort == 0 {
		panic("监听端口配置错误")
	}

}

func main(){
	log.Println("gitee hook 监听 启动")

	http.HandleFunc("/", hook.GiteeHook)

	http.ListenAndServe(":"+strconv.Itoa(sysConf.Sys.MonitorPort),nil)
	log.Println("gitee hook 监听 结束")
}







// 载入配置
func loadConf(path string)(b []byte, err error){
	fi, err := os.Stat(path)
	if err != nil {
		return nil, fmt.Errorf("配置文件未找到：%w", err)
	}
	file, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("配置 文件打开失败：%w", err)
	}
	defer file.Close()

	confStr := make([]byte, fi.Size())

	if _, err := file.Read(confStr); err != nil {
		return nil, fmt.Errorf("%v 配置读取失败,请确认配置格式：%w",path, err)
	}

	return confStr, nil
}